
import Form from "@hi-ui/form"
import Input from "@hi-ui/input"
import Checkbox from "@hi-ui/checkbox"
import message from "@hi-ui/message"
import React, { useEffect, useState } from 'react'
// 导入api
import userApi from '@/api/user'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
// 导入api
import { loginAsync } from '@/store/reducers/userSlice'

/**
 * @title 登录页面
 */
const Login = () => {
    // redux hook
    const dispatch = useDispatch()
    // router hook
    const navigate = useNavigate()
    const location = useLocation()

    const from = location.state?.preLocation?.pathname || '/home'
    // 按钮loading
    const [loading, setLoading] = useState(false)

    const FormItem = Form.Item
    const FormReset = Form.Reset
    const FormSubmit = Form.Submit

    const formRef = React.useRef(null)
    const [uuid, setUuid] = useState(undefined)
    const [verifyImg, setVerifyImg] = useState('')

    const onFinish = async (values) => {
        // 开始loading
        setLoading(true)
        // 记住密码存储用户信息
        if (values.remember) {
            localStorage.setItem('username', values.username)
            localStorage.setItem('password', values.password)
            localStorage.setItem('remember', String(values.remember))
        } else {
            // 移除用户信息
            localStorage.removeItem('username')
            localStorage.removeItem('password')
            localStorage.removeItem('remember')
        }
        try {
            await dispatch(loginAsync({ ...values, uuid }))
            setLoading(false)
            // 若上次为登录页，跳转到首页
            if (from === '/login') navigate('/home', { replace: true })
            else navigate(from, { replace: true })
            message.open({
                content: '登录成功',
                type: 'info'
            })
        } catch (e) {
            console.error(e)
            getCode()
            setLoading(false)
        }
    }
    // 获取验证码
    const getCode = () => {
        const uuid = new Date().getTime()
        setUuid(uuid)
        userApi.login.get(uuid).then((res) => {
            setVerifyImg(res.data)
        })
    }
    // 获取缓存中的用户名密码信息
    const getUser = () => {
        const username = localStorage.getItem('username') ?? ''
        const password = localStorage.getItem('password') ?? ''
        const remember = localStorage.getItem('remember') ?? false
        // 通过antd表单实例对象的setFieldsValue方法回显值
        formRef.current.setFieldsValue({
            username,
            password,
            remember: Boolean(remember)
        })
    }

    useEffect(() => {
        getCode()
        getUser()
    }, [])

    return (
        <div style={{
            minHeight: '100vh',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
        }}>
            <div style={{
                background: 'white',
                padding: '40px',
                borderRadius: '8px',
                boxShadow: '0 4px 20px rgba(0,0,0,0.1)',
                width: '400px',
                maxWidth: '90vw'
            }}>
                <div style={{ textAlign: 'center', marginBottom: '30px' }}>
                    <h1 style={{
                        color: '#333',
                        margin: '0 0 10px 0',
                        fontSize: '28px',
                        fontWeight: '600'
                    }}>HIUI 管理系统</h1>
                    <p style={{ color: '#666', margin: 0 }}>欢迎登录</p>
                </div>
                <Form
                    innerRef={formRef}
                    labelWidth="80"
                    labelPlacement="left"
                    initialValues={{
                        username: "",
                        password: "",
                        remember: true,
                    }}
                    onValuesChange={(changedValues, allValues) => {
                        console.log("changedValues:", changedValues, "allValues:", allValues)
                    }}
                    onSubmit={onFinish}
                >
                    <FormItem
                        label="用户名"
                        field={["username"]}
                        valueType="string"
                        rules={[
                            {
                                required: true,
                                validator: (rule, value, callback) => {
                                    const usernameReg = /^[a-zA-Z0-9_]{3,20}$/
                                    if (!value) {
                                        callback(new Error("请输入用户名"))
                                    } else if (!usernameReg.test(value)) {
                                        callback(new Error("用户名只能包含字母、数字、下划线，长度3-20位"))
                                    } else {
                                        callback()
                                    }
                                },
                            },
                        ]}
                    >
                        <Input placeholder="请输入用户名" />
                    </FormItem>
                    <FormItem
                        label="密码"
                        valueType="string"
                        field={["password"]}
                        rules={[
                            {
                                required: true,
                                validator: (rule, value, callback) => {
                                    if (!value) {
                                        callback(new Error("请输入密码"))
                                    } else if (value.length < 6) {
                                        callback(new Error("密码长度不能少于6位"))
                                    } else {
                                        callback()
                                    }
                                },
                            },
                        ]}
                    >
                        <Input type="password" placeholder="请输入密码" />
                    </FormItem>
                    <FormItem
                        label="验证码"
                        valueType="string"
                        field={["checkCode"]}
                        rules={[
                            {
                                required: true,
                                validator: (rule, value, callback) => {
                                    if (!value) {
                                        callback(new Error("请输入正确格式验证码"))
                                    } else if (value.length !== 4) {
                                        callback(new Error("验证码四位"))
                                    } else {
                                        callback()
                                    }
                                },
                            },
                        ]}
                    >

                        <Input type="checkCode" placeholder="请输入验证码" suffix={
                            <div
                                dangerouslySetInnerHTML={{ __html: verifyImg }}
                                className="login-captcha"
                                onClick={() => getCode()}></div>
                        } />
                    </FormItem>
                    <FormItem
                        field="remember"
                        valuePropName="checked"
                        valueType="boolean"
                        valueChangeFuncPropName="onChange"
                    >
                        <Checkbox>
                            记住我
                        </Checkbox>
                    </FormItem>
                    <FormItem valueType={null} field={null}>
                        <div style={{ display: 'flex', gap: '12px', justifyContent: 'center' }}>
                            <FormSubmit
                                type="primary"
                                style={{
                                    flex: 1,
                                    height: '40px',
                                    fontSize: '16px',
                                    fontWeight: '500'
                                }}
                                loading={loading}
                            >
                                登录
                            </FormSubmit>
                            <FormReset
                                style={{
                                    flex: 1,
                                    height: '40px',
                                    fontSize: '16px'
                                }}
                                onClick={() => {
                                    formRef.current?.resetFields?.()
                                    // 重置验证码输入并刷新验证码
                                    getCode()
                                    console.log("表单已重置")
                                }}
                            >
                                重置
                            </FormReset>
                        </div>
                    </FormItem>
                </Form>
            </div>
        </div>
    )
}

export default Login